using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.IRepository;
using SmartLink.Repository.Base;
using Dapper;
using System.Data.Common;
using SmartLink.EnumLibrary;

namespace SmartLink.Repository
{
    public class BIZ_UserToOrganizationRepo : RepositoryBase<BIZ_UserToOrganization>, IBIZ_UserToOrganizationRepo
    {
        public bool DeleteByUserId(int userId, DbTransaction tran = null)
        {
            using (var conn = CreateConn(tran))
            {
                var sql = "DELETE FROM BIZ_UserToOrganization WHERE userId=@UserId";
                int rows = conn.Execute(sql, new { UserId = userId }, tran);
                return rows > 0;
            }
        }

        public OrgStatusEnum GetUserOrginzationStatus(int userId)
        {
            var sql = @"select OrganizationStatus from biz_usertoorganization uto join biz_organization org 
                       on uto.oid = org.id where uto.userid = @userId";
            var parms = new { userId = userId };
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var result = conn.ExecuteScalar<OrgStatusEnum>(sql, parms);
                return result;
            }
        }

        public bool CheckExistUserUnderDept(int orgDeptId)
        {
            var sql = @"select count(*) from biz_usertoorganization uto inner join sys_user u 
                         on u.ID=uto.UserID where  OD_ID=@ODID and u.isDel=0";
            var parms = new { ODID = orgDeptId };
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var result = conn.ExecuteScalar<int>(sql, parms);
                return result > 0 ? true : false;
            }
        }

        public BIZ_UserToOrganization GetByUserId(int creator)
        {
            var sql = @"select * from BIZ_UserToOrganization where userId=@UserId";
            var param = new { UserId = creator };

            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var result = conn.QueryFirstOrDefault<BIZ_UserToOrganization>(sql, param);
                conn.Close();
                return result;
            }
        }
    }
}
